from flask import Blueprint, request, jsonify
from database.config import get_postgres_session
from database.models import KnowledgeBase, Document, User
from sqlalchemy.orm import joinedload
import uuid

kb_bp = Blueprint('knowledge_base', __name__)

@kb_bp.route('/knowledge-bases', methods=['GET'])
def get_knowledge_bases():
    """获取知识库列表"""
    session = get_postgres_session()
    try:
        search_term = request.args.get('search', '').lower()
        
        query = session.query(KnowledgeBase).options(joinedload(KnowledgeBase.owner))
        
        if search_term:
            query = query.filter(
                (KnowledgeBase.name.ilike(f'%{search_term}%')) |
                (KnowledgeBase.description.ilike(f'%{search_term}%'))
            )
        
        knowledge_bases = query.all()
        
        result = []
        for kb in knowledge_bases:
            # 计算实际文档数量
            doc_count = session.query(Document).filter_by(knowledge_base_id=kb.id).count()
            
            result.append({
                'id': kb.id,
                'name': kb.name,
                'description': kb.description,
                'docCount': doc_count,
                'lastUpdated': kb.updated_at.strftime('%Y-%m-%d') if kb.updated_at else None,
                'isPublic': kb.is_public,
                'owner': {
                    'id': kb.owner.id,
                    'name': kb.owner.name
                } if kb.owner else None
            })
        
        return jsonify({
            'success': True,
            'data': result
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
    finally:
        session.close()

@kb_bp.route('/knowledge-bases/<kb_id>', methods=['GET'])
def get_knowledge_base(kb_id):
    """获取单个知识库详情"""
    session = get_postgres_session()
    try:
        kb = session.query(KnowledgeBase).options(
            joinedload(KnowledgeBase.owner)
        ).filter_by(id=kb_id).first()
        
        if not kb:
            return jsonify({
                'success': False,
                'error': '知识库不存在'
            }), 404
        
        # 计算实际文档数量
        doc_count = session.query(Document).filter_by(knowledge_base_id=kb.id).count()
        
        result = {
            'id': kb.id,
            'name': kb.name,
            'description': kb.description,
            'docCount': doc_count,
            'lastUpdated': kb.updated_at.strftime('%Y-%m-%d') if kb.updated_at else None,
            'isPublic': kb.is_public,
            'createdAt': kb.created_at.strftime('%Y-%m-%d') if kb.created_at else None,
            'owner': {
                'id': kb.owner.id,
                'name': kb.owner.name
            } if kb.owner else None
        }
        
        return jsonify({
            'success': True,
            'data': result
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
    finally:
        session.close()

@kb_bp.route('/knowledge-bases', methods=['POST'])
def create_knowledge_base():
    """创建新知识库"""
    session = get_postgres_session()
    try:
        data = request.get_json()
        
        if not data or not data.get('name'):
            return jsonify({
                'success': False,
                'error': '知识库名称不能为空'
            }), 400
        
        # 生成新的知识库ID
        new_id = f"kb{uuid.uuid4().hex[:8]}"
        
        # 创建知识库
        kb = KnowledgeBase(
            id=new_id,
            name=data['name'],
            description=data.get('description', ''),
            is_public=data.get('isPublic', False),
            owner_id=data.get('ownerId', 1)  # 默认使用管理员用户
        )
        
        session.add(kb)
        session.commit()
        
        return jsonify({
            'success': True,
            'data': {
                'id': kb.id,
                'name': kb.name,
                'description': kb.description,
                'isPublic': kb.is_public
            }
        }), 201
        
    except Exception as e:
        session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
    finally:
        session.close()

@kb_bp.route('/knowledge-bases/<kb_id>', methods=['PUT'])
def update_knowledge_base(kb_id):
    """更新知识库"""
    session = get_postgres_session()
    try:
        kb = session.query(KnowledgeBase).filter_by(id=kb_id).first()
        
        if not kb:
            return jsonify({
                'success': False,
                'error': '知识库不存在'
            }), 404
        
        data = request.get_json()
        
        if data.get('name'):
            kb.name = data['name']
        if 'description' in data:
            kb.description = data['description']
        if 'isPublic' in data:
            kb.is_public = data['isPublic']
        
        session.commit()
        
        return jsonify({
            'success': True,
            'data': {
                'id': kb.id,
                'name': kb.name,
                'description': kb.description,
                'isPublic': kb.is_public
            }
        }), 200
        
    except Exception as e:
        session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
    finally:
        session.close()

@kb_bp.route('/knowledge-bases/<kb_id>', methods=['DELETE'])
def delete_knowledge_base(kb_id):
    """删除知识库"""
    session = get_postgres_session()
    try:
        kb = session.query(KnowledgeBase).filter_by(id=kb_id).first()
        
        if not kb:
            return jsonify({
                'success': False,
                'error': '知识库不存在'
            }), 404
        
        # 删除相关文档和切片
        documents = session.query(Document).filter_by(knowledge_base_id=kb_id).all()
        for doc in documents:
            # DocumentSlice会通过外键约束自动删除
            session.delete(doc)
        
        session.delete(kb)
        session.commit()
        
        return jsonify({
            'success': True,
            'message': '知识库删除成功'
        }), 200
        
    except Exception as e:
        session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
    finally:
        session.close()
